package dao

//这里写的有点乱，把createtoken那些也写在这里了

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/google/uuid"
	"log"
	"oidc/model"
	"oidc/service"
	"strings"
	"time"
)

func HandUUID(u string) (uuid string) {
	split := strings.Split(u, "-")

	for _, val := range split {
		uuid = uuid + val
	}
	return
}

var TokenDB = TokenCtl{
	AccessToken:  make(map[string]int), //token-userid
	RefreshToken: make(map[string]int), //token-userid
}

type AccessTokenBag struct { //Are，||AccessToken，RefreshToken和过期时间
	AToken  string
	RToken  string
	IdToken string
	ExTime  time.Time
}

type TokenCtl struct {
	AccessToken  map[string]int //token-userid
	RefreshToken map[string]int //token-userid
}

//返回AccessToken，RefreshToken和过期时间和idtoken
func (t *TokenCtl) CreateARIToken(info model.UserAuth) (Are AccessTokenBag, err error) {
	var claim service.AccessTokenClaims
	var idClaim = service.IdTokenClaims{
		Uid:            info.Identifier,
		UserNames:      info.UserName,
		Email:          info.Email,
		Phone:          info.Phone,
		StandardClaims: jwt.StandardClaims{},
	}

	aToken, err := claim.CreateToken()
	if err != nil {
		log.Println(err)
		return
	}

	idToken, err := idClaim.CreateToken()
	if err != nil {
		log.Println(err)
		return
	}
	Are.AToken = aToken.Token
	Are.RToken = HandUUID(uuid.New().String())
	Are.IdToken = idToken.Token
	Are.ExTime = aToken.ExpiresTime
	t.StoreAccessToken(&Are, info.Identifier)
	return
}

func (t *TokenCtl) StoreAccessToken(are *AccessTokenBag, uid int) { //储存aid和rid
	TokenDB.AccessToken[are.AToken] = uid
	TokenDB.AccessToken[are.RToken] = uid
}
